package vn.bang.xiangqi.server.business;

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.EntityManager;

import vn.bang.dao.DAOFactory;
import vn.bang.dao.PlayerDAO;
import vn.bang.entity.PlayerDTO;
import vn.bang.entity.UserDTO;
import vn.bang.utility.JpaUtil;

public class PlayerBusiness extends AbstractBaseBusiness {
	
	static public Collection<UserDTO> saveAll(Collection<PlayerDTO> players) {
		Collection<UserDTO> usersResult = new ArrayList<UserDTO>();
		boolean transactionFinished = Boolean.FALSE;
		EntityManager entityManager = createEntityManager();
		try {
			PlayerDAO playerDAO = DAOFactory.createPlayerDAO(entityManager);
			JpaUtil.beginTransaction(entityManager);
			for (PlayerDTO playerDTO : players) {
				playerDAO.save(playerDTO);
			}
			JpaUtil.commitEntityManager(entityManager);
			transactionFinished = Boolean.TRUE;
		} finally {
			JpaUtil.closeEntityManager(entityManager);
		}
		
		if (!transactionFinished) {
			JpaUtil.rollbackEntityManager(entityManager);
		}
		
		return usersResult;
	}
	
}
